package com.knowledgbase.springboot.aop.aspects;

import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Order(-1)
public class AppLogAspect {
	public static final Logger LOGGER = LoggerFactory.getLogger(AppLogAspect.class);
	
	@Pointcut("execution(* com.knowledgbase.springboot.aop.controller.AopController.*(..))")
	public void pointCut() {
	}
	
	@Before("pointCut()")
	public void doBefore(JoinPoint joinPoint) {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		// 记录请求的内容
        LOGGER.info("Request URL: {}", request.getRequestURL().toString());
        LOGGER.info("Request Method: {}", request.getMethod());
        LOGGER.info("IP: {}", request.getRemoteAddr());
        LOGGER.info("User-Agent:{}", request.getHeader("User-Agent"));
        LOGGER.info("Class Method:{}", joinPoint.getSignature().getDeclaringTypeName() + "."  + joinPoint.getSignature().getName());
        LOGGER.info("Cookies:{}", request.getCookies());
        LOGGER.info("Params:{}", Arrays.toString(joinPoint.getArgs()));
        
		Enumeration<String> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements()) {
			String paramName = parameterNames.nextElement();
			LOGGER.info(paramName+":"+request.getParameter(paramName));
		}
	}
	
}
